package com.com.effectivejava.commonmethods.equals;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by pankaj on 7/10/14.
 */
public class SymmetricProblemSolved {
    public static void main(String... a){
        CaseInsensitiveString2 cs = new CaseInsensitiveString2("Polish");
        String s = "polish";
        System.out.println("cs.equals(s) = " + cs.equals(s));
        System.out.println("s.equals(cs) = " + s.equals(cs));

        List<CaseInsensitiveString2> list = new ArrayList<CaseInsensitiveString2>();
        list.add(cs);
        System.out.println("list.contains(cs) = " + list.contains(cs));

        //list.contains(s) depends on equals method of s (String) to find if this
        // element is equal to any present in the list.

        //This is opposite to my assumption that equals method will be invoked on each element
        // present in the list. but instead equals method of String s will be called.

        // Very good example of symmetric problem.
        System.out.println("list.contains(s) = " + list.contains(s));
        /*
        list.contains(s)
        will invoke
        for(CaseInsensitiveString cs : list){
           if(s.equals(cs)){
             return true;

           }
        }
        return false;
        */


    }

}

 final class CaseInsensitiveString2 {
    private final String s;
    public CaseInsensitiveString2(String s) {
        if (s == null)
            throw new NullPointerException();
        this.s = s;
    }

    @Override public boolean equals(Object o) {
        if (o instanceof CaseInsensitiveString2)
            return s.equalsIgnoreCase(
                    ((CaseInsensitiveString2) o).s);

        return false;
    }

}